package com.dizang.sharding.common.repository.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;

import com.dizang.sharding.common.mapper.BaseMapper;
import com.dizang.sharding.common.repository.BaseRepository;
import com.dizang.sharding.common.repository.IPage;

/**
 * 
 * @author kelvin
 * @param <T>
 *
 */
public abstract class BaseRepositoryImpl<M extends BaseMapper<T>, T> implements BaseRepository<T> {

	@Autowired
	protected M baseMapper;

	/**
	 * 每个实现类都需要BaseDao
	 * 
	 * @return BaseMapper
	 */
	protected M getBaseMapper() {
		return this.baseMapper;
	}

	@Override
	public T selectOne(T arg0) {
		return this.getBaseMapper().selectOne(arg0);
	}

	@Override
	public List<T> select(T arg0) {
		return this.getBaseMapper().select(arg0);
	}

	@Override
	public List<T> selectAll() {
		return this.getBaseMapper().selectAll();
	}

	@Override
	public int selectCount(T arg0) {
		return this.getBaseMapper().selectCount(arg0);
	}

	@Override
	public T selectByPrimaryKey(Object arg0) {
		return this.getBaseMapper().selectByPrimaryKey(arg0);
	}

	@Override
	public boolean existsWithPrimaryKey(Object arg0) {
		return this.getBaseMapper().existsWithPrimaryKey(arg0);
	}

	@Override
	public int insert(T arg0) {
		return this.getBaseMapper().insert(arg0);
	}

	@Override
	public int insertSelective(T arg0) {
		return this.getBaseMapper().insertSelective(arg0);
	}

	@Override
	public int updateByPrimaryKey(T arg0) {
		return this.getBaseMapper().updateByPrimaryKey(arg0);
	}

	@Override
	public int updateByPrimaryKeySelective(T arg0) {
		return this.getBaseMapper().updateByPrimaryKeySelective(arg0);
	}

	@Override
	public int delete(T arg0) {
		return this.getBaseMapper().delete(arg0);
	}

	@Override
	public int deleteByPrimaryKey(Object arg0) {
		return this.getBaseMapper().deleteByPrimaryKey(arg0);
	}

	@Override
	public IPage<T> page(IPage<T> page, T queryWrapper) {
		int selectCount = this.getBaseMapper().selectCount(queryWrapper);
		page.setTotal(selectCount);
		List<T> selectByExample = this.getBaseMapper().selectPage(queryWrapper, page);
		page.setRecords(selectByExample);
		return page;
	}

	@Override
	@Transactional(rollbackOn=Exception.class)
	public int updateBatch(List<T> queryWrapper) {
		int count = 0;
		for (T t : queryWrapper) {
			int updateByPrimaryKeySelective = this.getBaseMapper().updateByPrimaryKeySelective(t);
			count+=updateByPrimaryKeySelective;
		}
		return count;
	}

}